#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
#include <unistd.h>
#include <sensor_manager.h>

static int fd;
static char g_humi, g_temp;

static int Dht11DeviceInit(void)
{
    fd = open("/dev/mydht11", O_RDWR | O_NONBLOCK);
    if (fd < 0)
    {
        printf("dht11 device open error\n");
        return -1;
    }
    else  printf("dht11 device open ok\n");
    return 0;
}

static int Dht11DeviceExit(void)
{
    return close(fd);
}

static int Dht11DataGetEvent(void);

static SensorDevice g_tSensorDev ={
	.name = "DHT11",
    .databuf = {0},
	.GetSensorDataEvent  = Dht11DataGetEvent,
	.DeviceInit     = Dht11DeviceInit,
	.DeviceExit     = Dht11DeviceExit,
};

static int Dht11DataGetEvent(void)
{
     static char buf[2] = {0};
     
     if (2 == read(fd, buf, 2))
	 {
		g_tSensorDev.databuf[0] = buf[0];
		g_tSensorDev.databuf[1] = buf[1];
        sprintf(g_tSensorDev.databuf,"%d",buf[0]);
        sprintf(&g_tSensorDev.databuf[2],"%d",buf[1]);
        printf("%s %d %s()\ndatabuf:%s\n",__FILE__, __LINE__, __FUNCTION__,g_tSensorDev.databuf);
        return 0;
	 } 
     printf("%s:%d %s()\nbuf[0]:%d,buf[1]:%d\n",__FILE__, __LINE__, __FUNCTION__,buf[0],buf[1]);
     return -1;   
}

void Dht11DeviceRegister(void)
{
    RegisterSensorDevice(&g_tSensorDev);
}



/************************************ */

// void *dht11_thread(void *arg)
// {
//     char buf[2];
//     while (1)
//     {
// 	    if (2 == read(fd, buf, 2))
// 	    {
// 		g_humi = buf[0];
// 		g_temp = buf[1];
// 		sleep(1);
// 	    }
//     }
// }

// void dht11_init(void)
// {
//     pthread_t tid1;
//     fd = open("/dev/mydht11", O_RDWR | O_NONBLOCK);
//     if (fd >= 0)
//     {
//         int ret = pthread_create(&tid1,NULL, dht11_thread,NULL);//创建线程
//     }

// }

// int dht11_read(char *humi, char *temp)
// {
//     *humi = g_humi;
//     *temp = g_temp;
//     return 0;
// }


